package chap3_4;

import java.io.*;

/**
 * @author https://gitee.com/W_Jun
 * @date 2021-12-13 16:49
 * @Description 字符流的编码解码
 */
public class ConversionStreamDemo {
    public static void main(String[] args) throws IOException {
        //1. 写数据
        //采用默认字符编码写数据
        /*FileOutputStream fos = new FileOutputStream("chapter03-字符流\\osw.txt");
        OutputStreamWriter osw = new OutputStreamWriter(fos);*/
        OutputStreamWriter osw1 = new OutputStreamWriter(new FileOutputStream("chapter03-字符流\\osw1.txt"));
        osw1.write("中国");
        osw1.close();

        //采用指定字符编码写数据-UTF-8
        OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream("chapter03-字符流\\osw2.txt"), "UTF-8");
        osw2.write("中国");
        osw2.close();

        //采用指定字符编码写数据-GBK
        OutputStreamWriter osw3 = new OutputStreamWriter(new FileOutputStream("chapter03-字符流\\osw3.txt"), "GBK");
        osw3.write("中国");
        osw3.close();

        //2. 读数据
        //使用默认字符集
        InputStreamReader isr = new InputStreamReader(new FileInputStream("chapter03-字符流\\osw1.txt"));
        int ch;
        while ((ch = isr.read()) != -1) {
            System.out.print((char) ch);
        }
        isr.close();
        System.out.println("---------");

        //指定字符集
        InputStreamReader isr3 = new InputStreamReader(new FileInputStream("chapter03-字符流\\osw3.txt"), "GBK");
        int ch3;
        while ((ch3 = isr3.read()) != -1) {
            System.out.print((char) ch3);
        }
        isr3.close();
    }
}
